interface StorageData {
  timestamp: number
  data: any
}
export enum ErrorStatus {
  InvalidKey = '1',
  InvalidValue = '2',
  TimeoutValue = '3'
}
const storage = {
  /** 
   * @author 刘建文
   * @createAt 2019-12-20 16:21:49
   * @param key key
   * @description 获取存储的storage
   */
  get(key: string) {
    try {
      if (!key) {
        throw new Error(ErrorStatus.InvalidKey)
      }
      const storageData = cc.sys.localStorage.getItem(key)
      if (!storageData) {
        throw new Error(ErrorStatus.InvalidKey)
      }
      const data: StorageData = JSON.parse(storageData)
      if (data.timestamp !== 0 && Date.now() > data.timestamp) {
        // this.remove(key)
        throw new Error(ErrorStatus.InvalidKey)
      }
      return data.data
    } catch (error) {
      cc.log(error)
      return null
    }
  },
  /** 
   * @author 刘建文
   * @createAt 2019-12-20 16:16:04
   * @param key 存储key
   * @param data 存储内容
   * @param time 过期时间，单位S；不过期不填
   * @description 存储storage
   */
  set(key: string, data: any, time?: number) {
    const timestamp = time ? Date.now() + time * 1000 : 0
    const saveData: StorageData = {
      timestamp,
      data
    }
    cc.sys.localStorage.setItem(key, JSON.stringify(saveData))
  },
  /** 
   * @author 刘建文
   * @createAt 2019-12-20 16:15:14
   * @param key key
   * @description 删除storage
   */
  remove(key: string) {
    cc.sys.localStorage.removeItem(key)
  }
}
export default storage
